package com.wms.service.impl;

import com.wms.entity.Store;
import com.wms.mapper.StoreMapper;
import com.wms.service.StoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class StoreServiceImpl implements StoreService {
    @Autowired
    StoreMapper storeMapper;

    @Override
    public int addStore(Store store) {
        return storeMapper.addStore(store);
    }

    //   查询所有仓库
    @Override
    public List<Map<String,Map>> chaCk() {
        return storeMapper.chaCk();
    }

    @Override
    public  List<Map<String,Map>> chaWq() {

        return storeMapper.chaWq();
    }

    @Override
    public List<Map<String, Object>> ckList() {
        return storeMapper.ckList();
    }

    @Override
    public List<Map<String, Object>> getStoreTree() {
        return storeMapper.ckTree();
    }


    @Override
    public List<Store> getAllStores() {
        return storeMapper.treeCK();
    }

    /**
     * 构建完整的树形结构
     *
     * @param nodeList 所有节点的平级列表（未分层的原始数据）
     * @param rootFId  根节点的父ID标识（通常根节点的父ID为0或null，根据业务定义）
     * @return 构建完成的树形结构根节点列表
     */
    @Override
    public List<Store> buildTree(List<Store> nodeList, Integer rootFId) {
        List<Store> list = new ArrayList<>();
        List<Store> list2 = nodeList.stream().
                filter(node -> rootFId.equals(node.getFuId())).
                collect(Collectors.toList());

        for (Store store : list2) {
            findChildren(store, nodeList);
            list2.add(store);
        }
        return list;
    }

    /**
     * 递归查找并设置父节点的子节点
     *
     * @param parent   父节点
     * @param nodeList 父节点的子节点集合
     */
    @Override
    public void findChildren(Store parent, List<Store> nodeList) {
        List<Store> list = new ArrayList<>();
        for (int i = 0; i < nodeList.size(); i++) {
            //获取每个节点
            Store store = nodeList.get(i);
            //判断该节点是否 是i的子节点
            if (parent.getId().equals(store.getFuId())) {
                list.add(store);
            }
            //有子节点则设置到父类中
            if (!list.isEmpty()) {
                parent.setStoreslist(list);
                //遍历 递归 所有层级
                for (int j = 0; j < list.size(); j++) {
                    Store ss = list.get(j);
                    findChildren(ss, nodeList);
                }
            }
        }
    }


    @Transactional
    @Override
    public int deleCkById(int id) {
        List<Store> list = storeMapper.selectZickById(id);
        if (!list.isEmpty()) {
            System.out.println("下级还有数据");
            throw new RuntimeException("下级还有数据");
        }
        return storeMapper.deleCkById(id);
    }


    public List<Store> WXTree() {
        return storeMapper.selectRootStores();
    }





}